package cn.liccshop.core.utils;

import cn.liccshop.sys.constants.Constants;
import cn.liccshop.sys.exception.MySystemException;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.math.BigInteger;

/**
 * @author LiCC
 * @program LiCCShop
 * @description 前段接收Map参数值转换
 * @since 2019-04-14-00:33
 */
public class ObjectToOtherUtils {

    /**
     * 转String
     * @param param
     * @return
     */
    public static String toString(Object param){
        if (param == null || StringUtils.isBlank(String.valueOf(param))){
            return null;
        }
        return String.valueOf(param);
    }

    /**
     * 转BigDecimal
     * @param param
     * @return
     * @throws MySystemException
     */
    public static BigDecimal toBigDecimal(Object param) throws MySystemException {
        BigDecimal ret = null;
        if (param != null){
            if (param instanceof BigDecimal) {
                ret = (BigDecimal) param;
            } else if (param instanceof String) {
                if (toString(param) != null){
                    ret = new BigDecimal(toString(param));
                }
            } else if (param instanceof BigInteger) {
                ret = new BigDecimal((BigInteger) param);
            } else if (param instanceof Number){
                ret = new BigDecimal(((Number) param).doubleValue());
            } else {
                throw new MySystemException("Not possible to coerce [" + param + "] from class " + param.getClass() + " into a BigDecimal.", Constants.INVALID_PARM);
            }
        }
        return ret;
    }

    /**
     * 转BigDecimal
     * @param param
     * @return
     */
    public static Integer toInteger(Object param) {
        if (param == null || toString(param) == null){
            return null;
        }
        return Integer.parseInt(toString(param));
    }
}
